package net.ib.mtalk.ui.inbox;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.UserBasicInfo;
import net.ib.mntalk.protocol.client.Database.ReceiverList;
import net.ib.mtalk.R;
import net.ib.mtalk.database.DatabaseContract.ViewTable;
import net.ib.mtalk.ui.attachment.emoticon.RichString;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import net.ib.mtalk.util.ProfileImageLoader;
import net.ib.mtalk.util.TimeAdapter;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.protobuf.micro.InvalidProtocolBufferMicroException;

public class InboxListCursorAdapter extends CursorAdapter {

	private int mLayout;

	public InboxListCursorAdapter(Context context, Cursor c) {
		super(context, c, true);
		mLayout = R.layout.list_item_inbox;
	}
    
	public InboxListCursorAdapter(Context context, Cursor c, int flag) {
		super(context, c, flag);
		mLayout = R.layout.list_item_inbox;
	}
	
	@Override
	public View newView(Context context, Cursor cursor, ViewGroup parent) {
		LayoutInflater inflater = LayoutInflater.from(context);
		View v = inflater.inflate(mLayout, parent, false);
		
		ViewHolder holder = new ViewHolder();
		holder.item = (RelativeLayout) v.findViewById(R.id.rLayoutFriend);
		holder.msgboxImageCheck = (ImageView) v.findViewById(R.id.msgboxImageCheck);
		holder.msgboxPushOnOff = (ImageView) v.findViewById(R.id.msgboxPushOnOff);
		holder.msgboxTextName = (TextView) v.findViewById(R.id.msgboxTextName);
		holder.msgboxMemeberCount = (TextView) v.findViewById(R.id.msgboxMemberCount);
		holder.msgboxLastTime = (TextView) v.findViewById(R.id.msgboxLastTime);
		holder.msgboxTextMessage = (TextView) v.findViewById(R.id.msgboxTextMessage);
		holder.msgboxUnreadCount = (TextView) v.findViewById(R.id.msgboxUnreadCount);
		
		v.setTag(holder);
		return v;
	}
	
	private static class ViewHolder {
		RelativeLayout item;
		ImageView msgboxImageCheck;
		ImageView msgboxPushOnOff;
		TextView msgboxTextName;
		TextView msgboxMemeberCount;
		TextView msgboxLastTime;
		TextView msgboxTextMessage;
		TextView msgboxUnreadCount;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (!mDataValid) {
            throw new IllegalStateException("this should only be called when the cursor is valid");
        }
        if (!mCursor.moveToPosition(position)) {
            throw new IllegalStateException("couldn't move cursor to position " + position);
        }
        
        View v;
        if (convertView == null) {
            v = newView(mContext, mCursor, parent);
        } else {
            v = convertView;
        }
        
        bindView(v, mContext, mCursor);
        return v;
	}
	
	@Override
	public void bindView(View view, Context context, Cursor cursor){
		ViewHolder holder = (ViewHolder)view.getTag();
		
		int viewUuidMsb = cursor.getColumnIndexOrThrow(ViewTable.KEY_VIEW_UUID_MSB);
		int viewUuidLsb = cursor.getColumnIndexOrThrow(ViewTable.KEY_VIEW_UUID_LSB);
		int receiverUuidMsb = cursor.getColumnIndexOrThrow(ViewTable.KEY_RECEIVER_UUID_MSB);
		int receiverUuidLsb = cursor.getColumnIndexOrThrow(ViewTable.KEY_RECEIVER_UUID_LSB);
		int title = cursor.getColumnIndexOrThrow(ViewTable.KEY_TITLE);
		int subTitle = cursor.getColumnIndexOrThrow(ViewTable.KEY_SUB_TITLE);
		int unreadCount = cursor.getColumnIndexOrThrow(ViewTable.KEY_VIEW_UNREAD_COUNT);
		int memberCount = cursor.getColumnIndexOrThrow(ViewTable.KEY_VIEW_MEMBER_COUNT);
		int timeStamp = cursor.getColumnIndexOrThrow(ViewTable.KEY_MESSAGE_LAST_TIME);
		int pushOnOff = cursor.getColumnIndexOrThrow(ViewTable.KEY_VIEW_PUSH_ONOFF);
		int receiverList = cursor.getColumnIndexOrThrow(ViewTable.KEY_RECEIVER_LIST);
		
		String memberList = null;
		
		if(cursor.getBlob(receiverList) != null){
			try {
				ReceiverList receiverlist = ReceiverList.parseFrom(cursor.getBlob(receiverList));
				for(UserBasicInfo info : receiverlist.getReceiverList()){
					if(memberList == null){
						memberList = info.getDisplayName();
					}else{
						memberList = memberList + ", " + info.getDisplayName();
					}
				}
			} catch (InvalidProtocolBufferMicroException e) {
				MTalkLogWriter.e(e);
			}
		}
		
		int enable = cursor.getInt(cursor.getColumnIndexOrThrow(ViewTable.KEY_VIEW_ENABLE));
		int chatType = cursor.getInt(cursor.getColumnIndexOrThrow(ViewTable.KEY_CHAT_TYPE));
		
		// 타입별 설정. 이미지! 아랫글
		if(chatType != 0){
			if(enable != ViewTable.EnableType.LEAVE.ordinal()){
				switch(chatType){
					case Common.ONE_TO_ONE:
						// 프로필을 설정한다.
						if(cursor.getLong(receiverUuidMsb) != 0
								&& cursor.getLong(receiverUuidLsb) != 0){
							ProfileImageLoader.getInstance(mContext).loadProfileImage(holder.msgboxImageCheck, 
									GpbSupport.UuidMsgToString(
											GpbSupport.makeUuidMsg(
													cursor.getLong(receiverUuidMsb), 
													cursor.getLong(receiverUuidLsb))));
						}else{
							holder.msgboxImageCheck.setImageResource(R.drawable.onetoone_pic);
						}
						// 아래 표시글 설정
						if(!cursor.isNull(subTitle)){
							holder.msgboxTextMessage.setText(new RichString(cursor.getString(subTitle)));
						}else{
							holder.msgboxTextMessage.setText(" ");
						}
						break;
					case Common.GROUP_CHAT:
						holder.msgboxImageCheck.setImageResource(R.drawable.group_pic);
						// 아래 표시글 설정
						if(memberList != null){
							holder.msgboxTextMessage.setText(memberList);
						}else{
							holder.msgboxTextMessage.setText(" ");
						}
						break;
					case Common.BROADCAST:
						holder.msgboxImageCheck.setImageResource(R.drawable.multi_pic);
						// 아래 표시글 설정
						if(memberList != null){
							holder.msgboxTextMessage.setText(memberList);
						}else{
							holder.msgboxTextMessage.setText(" ");
						}
						break;
					default:
						holder.msgboxImageCheck.setImageResource(R.drawable.onetoone_pic);
						// 아래 표시글 설정
						if(!cursor.isNull(subTitle)){
							holder.msgboxTextMessage.setText(new RichString(cursor.getString(subTitle)));
						}else if(memberList != null){
							holder.msgboxTextMessage.setText(memberList);
						}else{
							holder.msgboxTextMessage.setText(" ");
						}
						break;
				}
			}else{
				holder.msgboxImageCheck.setImageResource(R.drawable.exit_pic);
			}
		}
		// 타이틀 설정
		if(!cursor.isNull(title)){
			holder.msgboxTextName.setText(new RichString(cursor.getString(title)));
		}else{
			holder.msgboxTextName.setText(context.getString(R.string.inbox_chat_title));
		}
		
		// 읽지 않은 메시지 갯수 확인
		if(!cursor.isNull(unreadCount)){
			int unread = cursor.getInt(unreadCount);
			if(unread == 0){
				holder.msgboxUnreadCount.setVisibility(View.GONE);
			}else if(unread > 999){
				holder.msgboxUnreadCount.setVisibility(View.VISIBLE);
				holder.msgboxUnreadCount.setText("999");
			}else{
				holder.msgboxUnreadCount.setVisibility(View.VISIBLE);
				holder.msgboxUnreadCount.setText(unread+"");
			}
		}else{
			holder.msgboxUnreadCount.setVisibility(View.GONE);
		}
		// 푸쉬 받지 않기 아이콘 표시 여부 확인
		if(!cursor.isNull(pushOnOff)){
			int push = cursor.getInt(pushOnOff);
			if(push == ViewTable.PushType.ON.ordinal()){
				holder.msgboxPushOnOff.setVisibility(View.GONE);
			}else if(push == ViewTable.PushType.OFF.ordinal()){
				holder.msgboxPushOnOff.setVisibility(View.VISIBLE);
			}else{
				holder.msgboxPushOnOff.setVisibility(View.GONE);
			}
		}else{
			holder.msgboxPushOnOff.setVisibility(View.GONE);
		}
		// 참여자 수
		if(!cursor.isNull(memberCount)){
			int member = cursor.getInt(memberCount);
			if(member <= 2 && chatType == Common.ONE_TO_ONE){
				holder.msgboxMemeberCount.setVisibility(View.GONE);
			}else if(member > 1 && member < 1000){
				holder.msgboxMemeberCount.setVisibility(View.VISIBLE);
				holder.msgboxMemeberCount.setText("("+member+")");
			}else if(member > 999){
				holder.msgboxMemeberCount.setVisibility(View.VISIBLE);
				holder.msgboxMemeberCount.setText("(999)");
			}else{
				holder.msgboxMemeberCount.setVisibility(View.GONE);
			}
		}else{
			holder.msgboxMemeberCount.setVisibility(View.GONE);
		}
		// 날짜 표시 방법에 따른 표시
		if(!cursor.isNull(timeStamp)){
			long lastTime = cursor.getLong(timeStamp);
			long currentTime = System.currentTimeMillis();
			holder.msgboxLastTime.setVisibility(View.VISIBLE);
			switch(TimeAdapter.CompareTimeLong(lastTime, currentTime)){
				case TimeAdapter.DATE_CHANGED_NONE:
					holder.msgboxLastTime.setText(TimeAdapter.LongDate2Str(lastTime, "aa hh:mm "));
					break;
				case TimeAdapter.DATE_CHANGED_YEAR:
					holder.msgboxLastTime.setText(TimeAdapter.LongDate2Str(lastTime, "yyyy. M. d. "));
					break;
				case TimeAdapter.DATE_CHANGED_WEEK:
				case TimeAdapter.DATE_CHANGED_MONTH:
				case TimeAdapter.DATE_CHANGED_DAY_ONE:
				case TimeAdapter.DATE_CHANGED_DAY_TWO:
				case TimeAdapter.DATE_CHANGED_DAY_THREE:
				case TimeAdapter.DATE_CHANGED_DAY_FOUR:
				case TimeAdapter.DATE_CHANGED_DAY_FIVE:
				case TimeAdapter.DATE_CHANGED_DAY_SIX:
					holder.msgboxLastTime.setText(TimeAdapter.LongDate2Str(lastTime, "M. d. EEEE "));
					break;
				default:
					holder.msgboxLastTime.setText(TimeAdapter.LongDate2Str(lastTime, "aa hh:mm "));
					break;
			}
			
		}else{
			holder.msgboxLastTime.setVisibility(View.GONE);
		}
	}
	
	@Override
	public void changeCursor(Cursor cursor) {
		super.changeCursor(cursor);
	}
	
	@Override
	public Cursor swapCursor(Cursor c) {
		return super.swapCursor(c);
	}
	
	public void changeCursorAndColumns(Cursor c){
		super.changeCursor(c);
	}
	
	public static interface CursorToStringConverter{
		CharSequence convertToString(Cursor cursor);
	}
	
	public void setViewResource(int layout){
		mLayout = layout;
	}
}
